import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { BASE_URL, JWT_LS } from '../constants'
import { IProjectToEmployeeLink } from '../model/interfaces'

export const getTokenFromLocalStorage = () => {
    return localStorage.getItem(JWT_LS)
}

export const projectEmployeeLinksApi = createApi({
    reducerPath: 'projectEmployeeLinksApi',
    baseQuery: fetchBaseQuery(
        { baseUrl: `${BASE_URL}/projectEmployeeLink`, headers: {Authorization: `Bearer ${getTokenFromLocalStorage()}`}  }),
    tagTypes:['ProjectEmployeeLinks'],
    endpoints: (builder) => ({
        getProjectEmployeeLinks: builder.query<IProjectToEmployeeLink[], any>({
            query: (projectEmployeeLink: any ) => ({
                url: '',
                params: projectEmployeeLink
            }),
            providesTags:['ProjectEmployeeLinks'],
        }),
        createProjectEmployeeLinks: builder.mutation<void, IProjectToEmployeeLink>({
            query: (projectEmployeeLink: IProjectToEmployeeLink) =>  ({
                method: 'POST',
                url: '',
                body: projectEmployeeLink
            }),
            invalidatesTags: ['ProjectEmployeeLinks']
        }),
        updateProjectEmployeeLinks: builder.mutation<void, IProjectToEmployeeLink>({
            query: (projectEmployeeLink: IProjectToEmployeeLink) =>  ({
                method: 'PUT',
                url: `/${projectEmployeeLink._id}`,
                body: projectEmployeeLink
            }),
            invalidatesTags: ['ProjectEmployeeLinks']
        }),
        deleteProjectEmployeeLink: builder.mutation<void, IProjectToEmployeeLink>({
            query: (projectEmployeeLink: IProjectToEmployeeLink) => ({
                method: 'DELETE',
                url: `/${projectEmployeeLink._id}`
            }),
            invalidatesTags: ['ProjectEmployeeLinks']
        })
    }),
})

export const {
    useGetProjectEmployeeLinksQuery,
  useLazyGetProjectEmployeeLinksQuery,
  useUpdateProjectEmployeeLinksMutation,
  useCreateProjectEmployeeLinksMutation,
  useDeleteProjectEmployeeLinkMutation
} = projectEmployeeLinksApi
